//
//  FCWalletReceiveVC.m
//  FundChain
//
//  Created by 肖浩然的mac on 2018/3/2.
//  Copyright © 2018年 RUIXIN. All rights reserved.
//

#import "FCWalletReceiveVC.h"

@interface FCWalletReceiveVC ()<UIGestureRecognizerDelegate,UITextFieldDelegate>{
    UIView     *_viewNav;
    CIFilter   *_qrFilter;
    UIView     *_showView;
    
}
/* uiimageView */
@property (strong, nonatomic) UIImageView  *qrimageView;
/* 地址 */
@property (strong, nonatomic) UILabel *addressLabel;
/* 地址 */
@property (copy, nonatomic) NSString *addressStr;
/* 发送 */
@property (strong, nonatomic) UITextField *sendField;
/* 币种 */
@property (strong, nonatomic) UILabel *currencyLable;
/* price */
@property (strong, nonatomic) NSString *priceStr;
/* 接收 */
@property (strong, nonatomic)  UITextField *receiveField ;
@end

@implementation FCWalletReceiveVC


- (void)viewDidLoad {
    [super viewDidLoad];
 self.view.backgroundColor = kWhiteColor;
    [FCLocalUserHelper saveIsMainVC:@"0"];
    [self loadData];
    [self setupUI];
    
    
}
#pragma mark-获取数据源
-(void)loadData{
    
    FCAllAddressModel *model = [FCLocalUserHelper getFMDBAllAddressData:self.walletId];
    dispatch_async(dispatch_get_main_queue(), ^{
        self.addressLabel.text = model.address;
        
    });
    self.addressStr = model.address;
    
    FCBalanceModel *balanceModel =  [FCLocalUserHelper getFMDBBalanceData:self.walletId];
    
    
    NSArray *arr = balanceModel.currentResult;
    [arr enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        FCCurrentResultModel *model = [FCCurrentResultModel mj_objectWithKeyValues:obj];
        if ([model.currentId isEqualToString:@"8001"]) {
            
            
            self.priceStr = model.price;
            
        }
        
    }];
    dispatch_async(dispatch_get_main_queue(), ^{
    switch ([balanceModel.walletId integerValue]) {
        case 1001:
        {
            
            
            self.currencyLable.text = @"BTC";
            
        }
            break;
        case 1005:
        {
            
            self.currencyLable.text = @"LTC";
            
            
        }
            break;
        case 1006:
        {
            
            self.currencyLable.text = @"BCH";
            
        }
            break;
        case 1009:
        {
            
            self.currencyLable.text = @"CCH";
            
        }
            break;
        case 1010:
        {
            
            self.currencyLable.text =  @"ZEC";
            
        }
            break;
            
        default:
            break;
    }
    });
}
#pragma mark-设置输入框的限制
-(void)textFieldDidChange:(UITextField *)textField{
    if (self.sendField == textField) {
        
        //高精度计算法
        NSDecimalNumber *productPrice = [NSDecimalNumber decimalNumberWithString:[NSString stringWithFormat:@"%f",[self.sendField.text.trimWhitespace floatValue]]];
        
        NSDecimalNumber *productNumber = [NSDecimalNumber decimalNumberWithString:[NSString stringWithFormat:@"%.8f",[self.priceStr floatValue]]];
        NSDecimalNumber *totalAmount = [productPrice decimalNumberByMultiplyingBy:productNumber];
        self.receiveField.text = [NSString stringWithFormat:@"%@",totalAmount];
        NSLog(@"%@==%@====%@",productPrice,productNumber,totalAmount);
        
        FCCurrentResultModel *currentResultModel = self.currentResultModel;
        
        if ([currentResultModel.walletId isEqualToString:self.walletId]) {
            
            float result = [currentResultModel.price floatValue]*[self.sendField.text.trimWhitespace floatValue];
            self.receiveField.text = [NSString stringWithFormat:@"%.2f",result];
            
        }
        
    }
}
#pragma mark-拷贝地址
-(void)copyAddressBtnClick:(UIButton*)sender{
    
    if (self.addressStr == nil) {
        
        return;
    }else{
        
    }
    
    UIPasteboard *pab = [UIPasteboard generalPasteboard];
    NSString *string = self.addressStr;
    [pab setString:string];
    if (pab) {
       [self showMsg:Localized(@"成功") duration:2.0 imgName:@"success"];
    }else{
        [self showMsg:Localized(@"失败") duration:2.0 imgName:@"fail"];
    }
    
}
#pragma mark-设置UI
-(void)setupUI{
  
  //Myaddress
    UILabel *myAddressLabel = [UILabel new];
    [self.view addSubview:myAddressLabel];
    [myAddressLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(100*KScreenHeightScale1334);
        make.left.mas_equalTo(30*KScreenWidthScale750);
    }];
    myAddressLabel.text = Localized(@"我的地址");
    myAddressLabel.font = Kfont(32);
    myAddressLabel.textColor = kOrderColor;
    //address
    UILabel *addressLabel = [UILabel new];
    self.addressLabel = addressLabel;
    [self.view addSubview:addressLabel];
    [addressLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(myAddressLabel.mas_bottom).offset(30*KScreenHeightScale1334);
        make.left.mas_equalTo(30*KScreenWidthScale750);
        make.right.mas_equalTo(-30*KScreenWidthScale750);
    }];
//    addressLabel.text = @"1dfwr 5efo sdwy 15sd op5q hjet 53wq qdfxw";
    addressLabel.font = Kfont(28);
    addressLabel.numberOfLines = 2;
    addressLabel.textColor = kDarkBlackColor;
    
    //二维码
    //设置二维码容器视图
    UIImageView *qrimageView = [UIImageView new];
    self.qrimageView = qrimageView;
    qrimageView.userInteractionEnabled = YES;
    [self.view addSubview:qrimageView];
    [qrimageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.mas_equalTo(self.view).offset(-35);;
        make.centerX.mas_equalTo(0);
        make.size.mas_equalTo(CGSizeMake(200, 200));
        
    }];
    UILongPressGestureRecognizer *lpgr = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(qrimageViewLongPress:)];
    lpgr.minimumPressDuration = 0.5; //seconds  设置响应时间
    lpgr.delegate = self;
    [qrimageView addGestureRecognizer:lpgr];
    // 1.创建二维码过滤器
    CIFilter *qrFilter = [CIFilter filterWithName:@"CIQRCodeGenerator"];
    _qrFilter = qrFilter;
    // 2.设置默认值
    [_qrFilter setDefaults];
    // 3.打印输入的key
    //    NSLog(@"%@",qrFilter.inputKeys);
    /*
     inputMessage,         二维码信息
     inputCorrectionLevel  容错水平
     */
    // 4.设置二维码的信息
   
        
        
    [_qrFilter setValue:[[NSString stringWithFormat:@"%@",self.addressStr] dataUsingEncoding:NSUTF8StringEncoding] forKey:@"inputMessage"];
    
    [_qrFilter setValue:@"H" forKey:@"inputCorrectionLevel"];//设置二维码的纠错水平，越高纠错水平越高，可以污损的范围越大
    // 5.输出二维码图片
    CIImage *ciimage = _qrFilter.outputImage;
    
    ciimage = [ciimage imageByApplyingTransform:CGAffineTransformMakeScale(8, 8)];
    
    
    UIImage *uiimage = [UIImage imageWithCIImage:ciimage];
    // 6.开启图形上下文
    UIGraphicsBeginImageContext(uiimage.size);
    // 7.画二维码图片
    [uiimage drawInRect:CGRectMake(0, 0, uiimage.size.width, uiimage.size.height)];
    // 8.画图片
    CGFloat meImageW = 50;
    CGFloat meImageH = 50;
    CGFloat meImageX = (uiimage.size.width - meImageW) * 0.5;
    CGFloat meImageY = (uiimage.size.height - meImageH) * 0.5;
    UIImage *meImage = [UIImage imageNamed:@""];
    
    [meImage drawInRect:CGRectMake(meImageX, meImageY, meImageW, meImageH)];
    // 9.获取当前图形上下文中图片
    UIImage *finalImage = UIGraphicsGetImageFromCurrentImageContext();
    // 10.关闭图形上下文
    UIGraphicsEndImageContext();
    qrimageView.image = finalImage;
    
    //copy address
    UIButton *copyAddressBtn = [UIButton new];
    [self.view addSubview:copyAddressBtn];
    [copyAddressBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(30*KScreenWidthScale750);
        make.right.mas_equalTo(-30*KScreenWidthScale750);
        make.bottom.mas_equalTo(-300*KScreenHeightScale1334);
        make.height.mas_equalTo(112*KScreenHeightScale1334);
    }];
    copyAddressBtn.layer.cornerRadius = 5.0;
    copyAddressBtn.layer.masksToBounds = YES;
    copyAddressBtn.titleLabel.font = KOverstrikingfont(36);
    [copyAddressBtn setTitle:Localized(@"复制地址") forState:(UIControlStateNormal)];
    [copyAddressBtn setTitleColor:kWhiteColor forState:UIControlStateNormal];
    [copyAddressBtn setBackgroundColor:kLightblueColor];
    if (self.addressStr) {
      [copyAddressBtn setBackgroundColor:kRedOrangeColor];
    }
    
    //事件
    [copyAddressBtn addTarget:self action:@selector(copyAddressBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    
}
- (void)qrimageViewLongPress:(UILongPressGestureRecognizer *)gestureRecognizer {
    if ([gestureRecognizer state] == UIGestureRecognizerStateBegan ) {
        UIPasteboard *pab = [UIPasteboard generalPasteboard];
        NSString *string = self.addressStr;
        if (self.addressStr == nil) {
            return;
        }
        [pab setString:string];
        if (pab) {
            [self showMsg:Localized(@"成功") duration:2.0 imgName:@"success"];
        }else{
           [self showMsg:Localized(@"失败") duration:2.0 imgName:@"fail"];
        }
    }
}
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    //移除第一响应
    [self.sendField resignFirstResponder];
    
    
}
@end
